<template>
  <div class="login-page mx-auto p-3 w-330">
    <Validate-from @form-submit="onFormSubmit">
      <template #default>
        <div class="mb-3">
          <label for="exampleInputEmail1" class="form-label">电子邮箱</label>
          <Validate-input tag="input" :rules="emailRules" v-model="emailVal" placeholder="请输入电子邮箱地址" type="text"
            id="inp1"></Validate-input>
        </div>
        <div class="mb-3">
          <label for="exampleInputPassword1" class="form-label">密码</label>
          <Validate-input tag="input" :rules="passwordRules" v-model="passwordVal" placeholder="请输入密码" type="password"
            id="inp2"></Validate-input>
        </div>
      </template>
      <template #submit>
        <span class="btn btn-primary d-block ">登陆</span>
      </template>
    </Validate-from>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import ValidateFrom from '../components/ValidateFrom.vue';
import ValidateInput, { RuleProp } from '../components/ValidateInput.vue';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
import createMessage from '../components/createMessage';
// 邮箱验证
const emailRules: RuleProp[] = [
  { type: 'required', message: '电子邮箱不能为空' },
  { type: 'email', message: '请输入正确电子邮箱地址' },
]
// 密码验证
const passwordRules: RuleProp[] = [
  { type: 'required', message: '密码不能为空' },
  { type: 'range', max: { message: '您的密码至少8位', length: 8 }, min: { message: '您的密码最多6位', length: 6 } }
]
// 初始邮箱值
const emailVal = ref('')
// 初始密码值
const passwordVal = ref('')
const router = useRouter()
const store = useStore()
// form-submit 自定义事件的 触发函数， 子组件会触发这个事件， 并传递值
const onFormSubmit = (result: boolean) => {
  if (result) {
    store.dispatch('login', { email: emailVal.value, password: passwordVal.value }).then(() => {
      createMessage('登陆成功，两秒后跳转', 'success')
      setTimeout(() => {
        router.push({ name: 'home' })
      }, 2000);
    }).catch(e => {
      console.log(e);
    })
    // store.commit('login')
  }
}
</script>